﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using System.Web.Script.Serialization;
using Fuse8.ContentManagementFramework.Domain.Commands;
using Fuse8.ContentManagementFramework.Domain.Commands.CommandParameters;
using Fuse8.DomainFramework.BusinessService;

using Fuse8.ContentManagementFramework.Domain.Special;
using Fuse8.ContentManagementFramework.SystemFacade;
using Fuse8.DomainFramework.Common.Locator;

namespace Fuse8.ContentManagementFramework.Domain
{
    public partial class CmsSite
    {
        private IEnumerable<CmsDomain> _domains;

        public const string SitePropertiesKey = "cmsSiteProperties";

        [XmlIgnore]
        [ScriptIgnore]
        public IEnumerable<CmsConfigurationItem> SiteConfigurationItems
        {
            get
            {
                var container = GetMetaValue<CmsConfigurationItemContainer>(CmsConfiguration.SiteConfigurationElementMetaFieldName);

                return container != null ? container.Items : new List<CmsConfigurationItem>().ToArray();
            }
        }


        [XmlIgnore]
        [ScriptIgnore]
        public IEnumerable<CmsDomain> Domains
        {
            get
            {
                // note it is necessary to call ToList() to safely put _domains to cache or state server session
                if (_domains == null)
                {
                    var businessFacade = new BusinessServiceFacade<CmsDomain, int>();

                    var command = DependencyServiceLocator.Current.GetInstance<CmsDomainGetBySiteIdCommand>();

                    var commandParameter = new CmsDomainGetBySiteIdCommandParameter
                    {
                        SiteId = Id
                    };

                    command.ConfigureCommand(commandParameter);

                    _domains = businessFacade.Find(command).ToList();
                }

                return _domains;
            }
        }

        public CmsSite(int siteId)
        {
            var site = new BusinessServiceFacade<CmsSite, int>()
                .FindOne(siteId);

            if (site.IsCreated)
            {
                this.Id = site.Id;
                this.SiteName = site.SiteName;
                this.SiteGroup = site.SiteGroup;
                this.CreatedBy = site.CreatedBy;
                this.DateCreated = site.DateCreated;
                this.LastUpdatedBy = site.LastUpdatedBy;
                this.DateLastUpdated = site.DateLastUpdated;
            }
        }
    }
}
